package com.edu.msmservice.controller;

import com.edu.commonutils.R;
import com.edu.msmservice.service.MsmService;
import com.edu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmController
 * @date 2022/9/22 15:22
 * @Version 1.0
 */
//@CrossOrigin
@Api(description = "发送手机号验证码")
@RestController
@RequestMapping("/msmservice/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    @ResponseBody
    private R sendMsm(@PathVariable String phone){
        //获取随机数
        String random= RandomUtil.getFourBitRandom();
        Map<String,Object> map=new HashMap<>();
        map.put("code",random);

        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //短信发送
     Boolean boo=   msmService.send(map,phone);
     if(boo){
         //发送成功 把验证码放到redis里面并且设置有效时间
         redisTemplate.opsForValue().set(phone,random,5, TimeUnit.MINUTES);
         return R.ok();
     }else {
         return R.error().message("发送短信失败");
        }

    }

}
